package cn.linran.basic.controller;

import cn.linran.basic.util.FastDfsUtils;
import cn.linran.basic.util.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 注册店铺上传logo的接口
 */
@RestController // controller层，返回json格式数据
@RequestMapping("/fastdfs")
public class FastDfsController {
    /**
     * 前端选择图片后会自动调用此接口
     * @param file
     * @return
     */
    @PostMapping
    public JsonResult upload(@RequestPart(value = "file" , required = true) MultipartFile file){
        try {
            //1、获取原始文件名称  例如：sdasd.lsdd.jpg
            String originalFilename = file.getOriginalFilename();
            //2、获取文件的后缀，不要.
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);//例如：jpg
            //3、调用工具类的upload方法
            String path = FastDfsUtils.upload(file.getBytes(), substring);
            //4、把path放入，然后上传到前端
            return JsonResult.me().setResultObj(path);
        } catch (IOException e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("上传失败");
        }

    }

    /**
     * 选择照片以后移除照片后调用此接口
     */
    @DeleteMapping
    public JsonResult delete(@RequestParam(value = "path",required = true) String path){
        try {
            //假设：path为/group1/M00/00/E5/CgAIC2Lc_8-AOOAYAABYhGUbAYM031.jpg
            //1、截取掉'/'
            String pathTmp = path.substring(1);//此时pathTmp为group1/M00/00/E5/CgAIC2Lc_8-AOOAYAABYhGUbAYM031.jpg
            //2、得到组名
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //此时groupName为goup1
            //3、得到组名后面的虚拟路径
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);//此时remotePath为M00/00/E5/CgAIC2Lc_8-AOOAYAABYhGUbAYM031.jpg
            FastDfsUtils.delete(groupName,remotePath);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("删除失败");
        }
    }
}
















